# 之前学的代码:有没有切换.

# 切换
# def func1():
#     print('in func1')
#
# def func2():
#     print('in func2')
#     func1()
#     print('end')
#
# func2()

# 切换 + 保持状态

# def gen():
#     while 1:
#         yield 1
#
# def func():
#     obj = gen()
#     for i in range(10):
#         next(obj)
# func()

# 上面的例子遇到IO不能自动切换
# import time
# def gen():
#     while 1:
#         yield 1
#         time.sleep(0.5)
#
# def func():
#     obj = gen()
#     for i in range(10):
#         next(obj)
# func()

#
# 切换 +保持状态(遇到IO不会主动切换)

# from greenlet import greenlet
# import time
# def eat(name):
#     print('%s eat 1' %name)  # 2
#     # g2.switch('taibai')  # 3
#     time.sleep(3)
#     print('%s eat 2' %name)  # 6
#     g2.switch()  # 7
#
# def play(name):
#     print('%s play 1' %name)  # 4
#     g1.switch()  # 5
#     print('%s play 2' %name)  # 8
#
# g1=greenlet(eat)
# g2=greenlet(play)
#
# g1.switch('taibai')  # 1 切换到eat任务
import time

# 协程
# 模拟的阻塞,不是真正的阻塞
# import gevent
# from threading import current_thread
# def eat(name):
#     print('%s eat 1' %name)
#     print(current_thread().name)
#     # gevent.sleep(2)
#     time.sleep(2)
#     print('%s eat 2' %name)
#
# def play(name):
#     print('%s play 1' %name)
#     print(current_thread().name)
#     # gevent.sleep(1)
#     time.sleep(1)
#     print('%s play 2' %name)
#
#
# g1 = gevent.spawn(eat,'egon')
# g2 = gevent.spawn(play,name='egon')
# print(f'主{current_thread().name}')
# g1.join()
# g2.join()

# 最终版本:
import gevent
from gevent import monkey
monkey.patch_all()  # 打补丁: 将下面的所有的任务的阻塞都打上标记
def eat(name):
    print('%s eat 1' %name)
    time.sleep(2)
    print('%s eat 2' %name)

def play(name):
    print('%s play 1' %name)
    time.sleep(1)
    print('%s play 2' %name)


g1 = gevent.spawn(eat,'egon')
g2 = gevent.spawn(play,name='egon')

# g1.join()
# g2.join()
gevent.joinall([g1,g2])
